<script lang="ts" setup>
// @ts-ignore
import type { VbenDrawerInst } from '@vben/common-ui';
import type { UserDetail } from '#/api/system/user';

import { ElDescriptions, ElDescriptionsItem, ElEmpty, ElTag } from 'element-plus';
import { ref, unref } from 'vue';

import { getUserDetail } from '#/api/system/user';
import { $t } from '#/locales';

const emit = defineEmits(['register']);

const loading = ref(false);
const userDetail = ref<Partial<UserDetail>>({});

// 获取用户详情
const fetchUserDetail = async (id: string) => {
  try {
    loading.value = true;
    userDetail.value = await getUserDetail(id);
  } catch (error) {
    console.error('获取用户详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 状态文本映射
const getStatusText = (status: number) => {
  const statusMap: Record<number, { text: string; type: string }> = {
    0: { text: $t('system.user.status_type.normal'), type: 'success' },
    1: { text: $t('system.user.status_type.disabled'), type: 'danger' },
    2: { text: $t('system.user.status_type.locked'), type: 'warning' },
    3: { text: $t('system.user.status_type.inactive'), type: 'info' },
  };
  return statusMap[status] || { text: String(status), type: '' };
};

// 用户类型文本映射
const getUserTypeText = (userType: number) => {
  const typeMap: Record<number, { text: string; type: string }> = {
    0: { text: $t('system.user.userType_type.normal'), type: '' },
    1: { text: $t('system.user.userType_type.admin'), type: 'success' },
    2: { text: $t('system.user.userType_type.system'), type: 'warning' },
  };
  return typeMap[userType] || { text: String(userType), type: '' };
};

// 性别文本映射
const getGenderText = (gender: number) => {
  const genderMap: Record<number, string> = {
    0: $t('system.user.gender_type.unknown'),
    1: $t('system.user.gender_type.male'),
    2: $t('system.user.gender_type.female'),
  };
  return genderMap[gender] || String(gender);
};

// 关闭抽屉
function closeDrawer() {
  const drawerInstance = unref(drawerDialogRef);
  if (drawerInstance) {
    drawerInstance.closeDrawer();
  }
}

const drawerDialogRef = ref<VbenDrawerInst | null>(null);

// @ts-ignore
function register(instance) {
  drawerDialogRef.value = instance;
  emit('register', instance);
}

// 打开抽屉时的处理
// @ts-ignore
async function onDrawerOpened(data) {
  if (data && data.id) {
    await fetchUserDetail(data.id);
  }
}

defineExpose({
  setData: onDrawerOpened,
});
</script>

<template>
  <VbenDrawer
    v-bind="$attrs"
    @register="register"
    :title="$t('system.user.detail')"
    width="700px"
    :loading="loading"
  >
    <div v-if="userDetail.id" class="user-detail">
      <div class="user-header flex mb-6">
        <div class="avatar-container mr-4">
          <img
            v-if="userDetail.avatarUrl"
            :src="userDetail.avatarUrl"
            class="avatar"
            alt="User Avatar"
          />
          <div v-else class="avatar-placeholder"></div>
        </div>
        <div class="user-info flex-1">
          <h2 class="user-name text-lg font-bold">{{ userDetail.userName }}</h2>
          <div class="flex flex-wrap gap-2 mt-2">
            <el-tag :type="getStatusText(userDetail.status || 0).type" size="small">
              {{ getStatusText(userDetail.status || 0).text }}
            </el-tag>
            <el-tag :type="getUserTypeText(userDetail.userType || 0).type" size="small">
              {{ getUserTypeText(userDetail.userType || 0).text }}
            </el-tag>
            <el-tag v-if="userDetail.twoFactorEnabled" type="info" size="small">
              {{ $t('system.user.twoFactorEnabled') }}
            </el-tag>
          </div>
        </div>
      </div>

      <ElDescriptions :column="2" border>
        <ElDescriptionsItem :label="$t('system.user.userName')">
          {{ userDetail.userName }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.realName')">
          {{ userDetail.realName || '-' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.nickName')">
          {{ userDetail.nickName || '-' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.email')">
          <div class="flex items-center">
            {{ userDetail.email || '-' }}
            <el-tag v-if="userDetail.emailConfirmed" size="small" type="success" class="ml-2">
              {{ $t('system.user.confirmed') }}
            </el-tag>
          </div>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.phoneNumber')">
          <div class="flex items-center">
            {{ userDetail.phoneNumber || '-' }}
            <el-tag v-if="userDetail.phoneNumberConfirmed" size="small" type="success" class="ml-2">
              {{ $t('system.user.confirmed') }}
            </el-tag>
          </div>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.gender')">
          {{ getGenderText(userDetail.gender || 0) }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.birthDate')">
          {{ userDetail.birthDate || '-' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.createdTime')">
          {{ userDetail.createdTime }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.lastLoginTime')">
          {{ userDetail.lastLoginTime || '-' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.lastLoginIp')">
          {{ userDetail.lastLoginIp || '-' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.lastPasswordChangedTime')">
          {{ userDetail.lastPasswordChangedTime || '-' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.requiresPasswordReset')" :span="2">
          <el-tag :type="userDetail.requiresPasswordReset ? 'danger' : 'success'" size="small">
            {{ userDetail.requiresPasswordReset ? $t('common.yes') : $t('common.no') }}
          </el-tag>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.roles')" :span="2">
          <div v-if="userDetail.roles && userDetail.roles.length > 0" class="flex flex-wrap gap-1">
            <el-tag
              v-for="role in userDetail.roles"
              :key="role"
              size="small"
              class="mr-1 mb-1"
            >
              {{ role }}
            </el-tag>
          </div>
          <ElEmpty v-else :description="$t('system.user.noRoles')" />
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="$t('system.user.biography')" :span="2">
          <div class="biography-content">
            {{ userDetail.biography || '-' }}
          </div>
        </ElDescriptionsItem>
      </ElDescriptions>
    </div>
  </VbenDrawer>
</template>

<style scoped>
.user-detail {
  width: 100%;
}

.avatar-container {
  width: 80px;
  height: 80px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #f0f2f5;
  border: 1px solid #eee;
}

.biography-content {
  white-space: pre-line;
  line-height: 1.5;
  max-height: 120px;
  overflow-y: auto;
}
</style>
